package com.think.teaching.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.think.teaching.mapper.TagMapper;
import com.think.teaching.model.Tag;
import com.think.teaching.service.TagService;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 * 课程标签 服务实现类
 * </p>
 *
 * @author think
 * @since 2020-08-12
 */
@Service
public class TagServiceImpl extends BaseServiceImpl<TagMapper, Tag> implements TagService {

	@Override
	public Tag AddTag(Tag tag) {
		if (this.save(tag)) {
			return tag;
		}
		return null;
	}


	@Override
	public Tag UpdateTag(Tag tag) {
		if (this.updateById(tag)) {
			return tag;
		}
		return null;
	}

	@Override
	public Tag GetTag(Integer id,Boolean withoutBan) {
		QueryWrapper<Tag> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("id", id).ne("delflag", 1);
		if (withoutBan) {
			queryWrapper.eq("state", 1);
		}
		return getOne(queryWrapper);
	}

	@Override
	public Tag SetTagState(Integer id, Integer state) {
		UpdateWrapper<Tag> queryWrapper = new UpdateWrapper<>();
		queryWrapper.eq("id", id).ne("delflag", 1).set("state", state);
		this.update(queryWrapper);
		return getById(id);
	}

	@Override
	public IPage<Tag> ListTagWithTagAndType(Integer count, Integer page, Integer type,
			Boolean withoutBan) {
		QueryWrapper<Tag> queryWrapper = new QueryWrapper<>();
		queryWrapper.ne("delflag", 1).eq("type", type);
		if (withoutBan) {
			queryWrapper.eq("state", 1);
		}
		IPage<Tag> ipage = new Page<>(page, count);
		return this.page(ipage,queryWrapper);
	}

	@Override
	public List<Tag> ListTagSearch(String key,Integer type, Boolean withoutBan) {
		QueryWrapper<Tag> queryWrapper = new QueryWrapper<>();
		
		queryWrapper.ne("delflag", 1).eq("type", type).like("tag", key);	
		
		if (withoutBan) {
			queryWrapper.eq("state", 1);
		}
		queryWrapper.last("limit 0,10");
		return list(queryWrapper);
	}
	
	public Tag GetTagByTypeAndName(Integer type,String tag) {
		QueryWrapper<Tag> queryWrapper = new QueryWrapper<>();
		queryWrapper.ne("delflag", 1).eq("type", type).eq("tag", tag);
		return this.getOne(queryWrapper);
	}

	public Boolean CheckTagExist(Integer id){
		if(id<=0)
			return true;
		else{
			QueryWrapper<Tag> queryWrapper=new QueryWrapper<>();
			queryWrapper.eq("id",id).eq("delflag",0).eq("state",1);
			return getOne(queryWrapper)!=null;
		}
	}
}
